// Fill out your copyright notice in the Description page of Project Settings.


#include "KnifeBaseCpp.h"

#include "AttackComponentBaseCpp.h"
#include "GameModeBaseCpp.h"
#include "PlayerBaseCpp.h"
#include "PlayerStateBaseCpp.h"

AKnifeBaseCpp::AKnifeBaseCpp()
{
	PrimaryActorTick.bCanEverTick = true;
	Lock = true;
	Tags.Add(FName("Knife"));
}

void AKnifeBaseCpp::BeginPlay()
{
	Super::BeginPlay();
	FScriptDelegate BoxOverlapDelegate;
	BoxOverlapDelegate.BindUFunction(this, "OnPlayerOverlapStart");
	BoxCollider->OnComponentBeginOverlap.Add(BoxOverlapDelegate);
}

void AKnifeBaseCpp::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);
	if (Lock)
	{
		return;
	}
	const FVector CurrentLocation = GetActorLocation();
	SetActorLocation(CurrentLocation + FlyDirection * FlySpeed * DeltaSeconds);
}

void AKnifeBaseCpp::SetFlyParam(const FVector Location, const FVector Direction)
{
	FlyDirection = Direction;
	Lock = false;
	SetActorHiddenInGame(false);
	SetKnifeDirection(Direction.X);
	SetActorLocation(Location);
}

void AKnifeBaseCpp::OnPlayerOverlapStart(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	if (OtherActor == nullptr)
	{
		return;
	}
	if (!OtherActor->ActorHasTag(FName("Player")) && !OtherActor->ActorHasTag(FName("NPCArea")))
	{
		AGameModeBaseCpp* CurrentGameMode = Cast<AGameModeBaseCpp>(UGameplayStatics::GetGameMode(GetWorld()));
		CurrentGameMode->TryPutKnifeObjToPool(this);
		if (OtherActor->ActorHasTag(FName("NPC")))
		{
			APlayerBaseCpp* CurrentPlayer = Cast<APlayerBaseCpp>(GetWorld()->GetFirstPlayerController()->GetPawn());
			CurrentPlayer->GetAttackComponent()->ApplyDamage(OtherActor, EAttackMode::E_ProAttack);
		}
	}
}

void AKnifeBaseCpp::SetLock()
{
	Lock = true;
	SetActorHiddenInGame(true);
}

void AKnifeBaseCpp::SetMagicColor(const bool Use) const
{
	if (Use)
	{
		SpriteComponent->SetSpriteColor(FLinearColor::Red);
	}
	else
	{
		SpriteComponent->SetSpriteColor(FLinearColor::White);
	}
}

